package com.uuah.server.config.spring;

import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.uuah.utils.IOUtils;

/**
 *
 * TODO comment ...
 *
 * <p>
 * update record:updator，update time，update content and version
 * </p>
 *
 * @author <a href="jonny_quan@hotmail.com">jonny</a>
 * @date 2009 2009-3-27 下午01:25:54
 * @version 1.0.0
 */
public class UuahResourceLoader extends DefaultResourceLoader implements
		ResourcePatternResolver {
	protected transient Logger logger = LoggerFactory
			.getLogger(UuahResourceLoader.class);

	public Resource getResource(String rsc) {
		return getResourceByPath(rsc);
	}

	protected Resource getResourceByPath(String path) {
		InputStream is = null;
		try {
			is = IOUtils.getResourceAsStream(path, getClass());
		} catch (IOException e) {
			logger.error("Unable to load Spring resource " + path + " : "
					+ e.getMessage());
			return null;
		}

		if (is != null) {
			return new InputStreamResource(is);
		} else {
			logger.error("Unable to locate Spring resource " + path);
			return null;
		}
	}

	public Resource[] getResources(String rsc) throws IOException {
		if (rsc == null) {
			throw new IOException("No resources to read");
		}
		String[] resourcesNames = org.springframework.util.StringUtils
				.tokenizeToStringArray(rsc, ",;", true, true);
		Resource[] resources = new Resource[resourcesNames.length];
		for (int i = 0; i < resourcesNames.length; ++i) {
			resources[i] = getResourceByPath(resourcesNames[i]);
		}
		return resources;
	}
}
